import router from './router'
import store from './store'
import {getToken} from "./utils/auth";
import {timer} from "rxjs";
import Vue from 'vue';

const whiteList = [
  '/login',
];
const requireAdmin = [
  '/member',
];

const startLoading = () => {
  store.commit('app/set_loading', true);
};

const stopLoading = () => {
  timer(1000).subscribe(() => {
    store.commit('app/set_loading', false);
  })
};

router.beforeEach((to, from, next) => {
  startLoading();
  const token = getToken();
  if (token) {
    if (to.path === '/login') {
      next({path: '/home'})
      stopLoading()
    }
    else {
      store.dispatch('user/getUser').then(user => {
        if (user.suspended) {
          Vue.toasted.error('User has been suspended');
          store.dispatch('user/logout').then(() => {
            next('/login');
            stopLoading();
          }).catch(err => Vue.toasted.error(err));
        }
        if (requireAdmin.indexOf(to.path) !== -1) {
          if (user.admin) next();
          else {
            Vue.toasted.error('Permission denied');
            next('/home');
            stopLoading();
          }
        }
        else next();
      }).catch(err => {
        Vue.toasted.error(err);
      })

    }
  }
  else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    }
    else {
      next('/login');
      stopLoading();
    }
  }
});

router.afterEach(() => {
  stopLoading();
});
